package com.utils;

import com.config.RCjavaConfiguration;
import lombok.SneakyThrows;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 配置文件工具类
 * getPropsConfig：返回PropertiesConfiguration
 *
 * @author zyf
 */
public class ConfigUtil {

    private static ConfigUtil instance = null;

    private static Map propMap = new ConcurrentHashMap<String, HashMap>();

    public PropertiesConfiguration rcJavaConfig;

    private ConfigUtil() {
    }

    // lazy单例模式，默认的实例就是加载的"rcjava.properties"
//    @SneakyThrows(ConfigurationException.class)
    public static ConfigUtil getInstance() {
        synchronized (ConfigUtil.class) {
            if (instance == null) {
                instance = new ConfigUtil();
                // 创建一个新实例
//                instance.rcJavaConfig = new PropertiesConfiguration("rcjava.properties");
                // 使用RCjavaConfiguration中构建的全局实例globalConfig
                instance.rcJavaConfig = RCjavaConfiguration.globalConfig;
            }
            return instance;
        }
    }

    /**
     * 根据properties文件路径，获取属性对象
     *
     * @param propName
     * @return
     */
    public static PropertiesConfiguration getPropsConfig(String propName) {
        if (!propMap.containsKey(propName)) {
            instance.putConf(propName);
        }
        return (PropertiesConfiguration) propMap.get(propName);
    }

    /**
     * 将配置文件写到全局map
     *
     * @param propName
     */
    private static void putConf(String propName) {
        try {
            PropertiesConfiguration configuration = new PropertiesConfiguration(propName);
            propMap.put(propName, configuration);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    public PropertiesConfiguration getRcJavaConfig() {
        return rcJavaConfig;
    }
}
